package edu.office.applicationRepository;

import edu.office.entities.School;
import edu.office.entities.Student;
import edu.office.tools.EOMessage;
import edu.office.tools.EOMessage1;
import edu.office.tools.StaticFields;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.servlet.http.Part;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellAddress;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

@Named("studentRepositoryA")
@ApplicationScoped
public class StudentRepository extends ApplicationCommonRepository<Student> {
    @Inject
    RoleinfoRepository roleinfoRepository;
    @Inject
    UserRepository userRepository;
    private Student nullStudent;

    public Student getNullStudent() {
        if (null == nullStudent) {
            nullStudent = find("select * from student where name='SNULL'").firstResult();
        }
        return nullStudent;
    }

    public List<Student> getStudents(School school) {
        return list("SCHOOL_ID", school.getID());
    }

    public List<Student> search(String searchName, School school) {
        List<Student> searchedStudentList = new LinkedList<>();
        String schoolCondstring = "", searchCondString = "";
        if (school != null) {
            schoolCondstring = " school_id=" + school.getID();
        }
        searchCondString = " locate('" + searchName.trim() + "',name)>0 or "
                + " locate('" + searchName.trim().toLowerCase() + "',LOWER(FIRSTNAME))>0 or "
                + " locate('" + searchName.trim().toLowerCase() + "',LOWER(SECONDNAME))>0 or "
                + " locate('" + searchName.trim().toLowerCase() + "',LOWER(EMAIL))>0 or "
                + " locate('" + searchName.trim().toLowerCase() + "',LOWER(PHONE))>0";
        String condtionString = "";
        if (schoolCondstring.isEmpty()) {
            condtionString = searchCondString;
        } else {
            condtionString = schoolCondstring + " and " + searchCondString;
        }
        searchedStudentList.clear();
        List<Student> tem = find("select * from student where " + condtionString).list();
        tem.forEach(e -> {
            searchedStudentList.add((Student) e);
        });
        return searchedStudentList;
    }

    public String myCreate(Student student) {
        //1. check whether the name existed? If true, deny the operation;else continue;
        if (find("NAME", student.getNAME()).list().isEmpty()) {
            student.setPassword(StaticFields.encrypt(student.getPassword()));
            create(student);
            return EOMessage.getEOMessageENUM(EOMessage1.Succeed);
        } else {
            return EOMessage.getEOMessageENUM(EOMessage1.Already_Exist);
        }
    }

    public String studentsUpload(Part studentExcelFile, School school) {
        int i = 0;
        try {
            InputStream ins = studentExcelFile.getInputStream();
            Workbook book = new HSSFWorkbook(ins);
            Sheet sheet = book.getSheetAt(0);
            Row row = sheet.getRow(0);
            int columnum = row.getLastCellNum();//得到列数
            int rownum = sheet.getLastRowNum();//得到行数
            if (columnum != StaticFields.COLUMNNUM3 && columnum != StaticFields.COLUMNNUM5) {
                return EOMessage.getEOMessageENUM(EOMessage1.ExcelWrong1);
            } else {
                try {
                    for (; i < rownum; i++) {
                        if (find("select * from student where name='"
                                + sheet.getCellComment(new CellAddress(0, i)).getString().getString().trim() + "'").list().isEmpty()) {
                            Student student = new Student();
                            student.setNAME(sheet.getCellComment(new CellAddress(0, i)).getString().getString().trim());
                            String temName = sheet.getCellComment(new CellAddress(1, i)).getString().getString().trim();
                            student.setSecondname(temName.substring(0, 1));
                            student.setFirstname(temName.substring(1));
                            student.setPassword(StaticFields.encrypt(sheet.getCellComment(new CellAddress(2, i)).getString().getString().trim()));
                            if (columnum > StaticFields.COLUMNNUM5) {
                                student.setEmail(sheet.getCellComment(new CellAddress(3, i)).getString().getString().trim());
                                student.setPHONE(sheet.getCellComment(new CellAddress(4, i)).getString().getString().trim());
                            }
                            student.setSCHOOL_ID(school.getID());
                            student.setRoleId(roleinfoRepository.getStudentRoleinfo().getID());
                            create(student);
                        } else {
                            return sheet.getCellComment(new CellAddress(0, i)).getString().getString() + EOMessage.getEOMessageENUM(EOMessage1.Exist);
                        }
                    }

                } catch (Exception e) {
                    System.out.println("i=-1");
                    i = -1;
                } finally {
                    book.close();
                }
            }
        } catch (IOException ex) {
            System.out.println("i=-2");
            i = -2;
        }
        switch (i) {
            case -2:
                return EOMessage.getEOMessageENUM(EOMessage1.ExcelWrong3);
            case -1:
                return EOMessage.getEOMessageENUM(EOMessage1.ExcelWrong2);
            case 0:
                return EOMessage.getEOMessageENUM(EOMessage1.Empty);
            default:
                return EOMessage.getEOMessageENUM(EOMessage1.Succeed);
        }
    }

    private String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

    public String getTemplateOfStudent() {
        return "Studentnumber" + "\tName1" + "\tPassword" + "\tEmail" + "\t Phone" + "\t Phonenumber";
    }

    public String exeChangePassword(Student student, String oldPassword, String newPassword) {
        return userRepository.exeChangePassword(student, oldPassword, newPassword);
    }

}
